package com.cqjtu.store.interceptors;

import com.cqjtu.store.common.JwtUtils;
import com.cqjtu.store.common.ServiceCode;
import com.cqjtu.store.common.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ProjectName: cqjtu-store
 * @Titile: TokenHandlerInterceptor
 * @Author: Lucky
 * @Description: token拦截器
 */
@Slf4j
@Component
public class TokenHandlerInterceptor implements HandlerInterceptor {
    //前置
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.debug("开始拦截.....");
        //获取用户的token
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasText(token)){
            //token为空
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"token不能为空");
        }
        //token不为空
        //校验token的合法性
        JwtUtils.verifyToken(token);
        //token是ok的
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
